import { defineStore } from 'pinia'
import { login } from '@/api/modules/user'
import { navTabStore } from './navTab'
// console.log(login)
export const userStore =
    defineStore({
        id: 'userInfo',
        state() {
            return {
                userObj: {},
                cookie: '',
                token: localStorage.getItem('uk.token') || '',
                server: JSON.parse(localStorage.getItem('uk.server') || '{}'),
                extention: JSON.parse(localStorage.getItem('uk.extention') || '{}'),
                userInfo: JSON.parse(localStorage.getItem('uk.userInfo') || '{}')
            }
        },
        actions: {
            // 登录
            userLogin(userInfo) {
                const username = userInfo.username.trim()
                const password = userInfo.password

                return login({ ...userInfo, username, password }).then((data) => {
                    this.token = data.token
                    this.server = data.server
                    this.extention = data.extention
                    this.userInfo = data.data
                    localStorage.setItem('uk.token', this.token)
                    localStorage.setItem('uk.server', JSON.stringify(this.server))
                    localStorage.setItem('uk.userInfo', JSON.stringify(this.userInfo))
                    localStorage.setItem('uk.extention', JSON.stringify(this.extention))
                })
            },
            setUserInfo(val) {
                this.userObj = val
            },
            clearUserInfo() {
              const useNavTabStore = navTabStore()
              useNavTabStore.deleteActiveRouterName();
                this.userObj = {}
                this.token = {}
                this.server = {}
                this.extention = {}
                this.userInfo = {}
                localStorage.removeItem('uk.token')
                localStorage.removeItem('uk.server')
                localStorage.removeItem('uk.userInfo')
                localStorage.removeItem('uk.extention')
            },
        },
        persist: {
            enabled: true,
        }
    })
